import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
} from '@mui/material';
import { Line } from 'react-chartjs-2';
import { Product, YieldCalculation, RateRecord } from '../../types/product';
import { calculateWeightedYield, analyzeProfitVolatility } from '../../utils/calculations';

interface YieldCalculatorProps {
  product: Product;
}

const YieldCalculator: React.FC<YieldCalculatorProps> = ({ product }) => {
  const [calculation, setCalculation] = useState<YieldCalculation | null>(null);
  const [isVolatile, setIsVolatile] = useState(false);
  const [deviation, setDeviation] = useState(0);

  useEffect(() => {
    if (product.investments?.length > 0) {
      // 假设这里从产品数据中获取总收益
      const totalProfit = 21.82; // 示例数据，实际应从产品收益记录中计算

      const result = calculateWeightedYield(product.investments, totalProfit);
      setCalculation(result);

      // 分析收益波动
      const dailyProfits = product.historyRates.map((rate: RateRecord) =>
        rate.dailyProfit || (rate.advertisedRate / 365 * 10000)
      );
      const volatilityResult = analyzeProfitVolatility(dailyProfits);
      setIsVolatile(volatilityResult.isVolatile);
      setDeviation(volatilityResult.deviation);
    }
  }, [product]);

  // 图表数据
  const chartData = {
    labels: product.historyRates.map((rate: RateRecord) =>
      new Date(rate.startDate).toLocaleDateString()
    ),
    datasets: [
      {
        label: '宣传年化率',
        data: product.historyRates.map((rate: RateRecord) => rate.advertisedRate),
        borderColor: 'rgb(255, 99, 132)',
        backgroundColor: 'rgba(255, 99, 132, 0.5)',
      },
      {
        label: '实际年化率',
        data: product.historyRates.map((rate: RateRecord) => rate.rate),
        borderColor: 'rgb(53, 162, 235)',
        backgroundColor: 'rgba(53, 162, 235, 0.5)',
      },
    ],
  };

  const options = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top' as const,
      },
    },
    scales: {
      y: {
        beginAtZero: true,
      },
    },
  };

  if (!calculation) {
    return (
      <Typography color="textSecondary">
        暂无投资记录，无法计算收益
      </Typography>
    );
  }

  return (
    <Box>
      <TableContainer component={Paper} sx={{ mb: 4 }}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>指标</TableCell>
              <TableCell>预期值</TableCell>
              <TableCell>实际值</TableCell>
              <TableCell>差异</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            <TableRow>
              <TableCell>年化收益率</TableCell>
              <TableCell>
                {product.historyRates[0]?.advertisedRate.toFixed(2)}%
              </TableCell>
              <TableCell>{calculation.annualizedRate.toFixed(2)}%</TableCell>
              <TableCell>
                {(calculation.annualizedRate -
                  (product.historyRates[0]?.advertisedRate || 0)).toFixed(2)}%
              </TableCell>
            </TableRow>
            <TableRow>
              <TableCell>万份收益</TableCell>
              <TableCell>
                {product.historyRates[0]?.dailyProfit?.toFixed(2) || '-'}
              </TableCell>
              <TableCell>
                {calculation.dailyProfitPerTenThousand.toFixed(2)}
              </TableCell>
              <TableCell>
                {(calculation.dailyProfitPerTenThousand -
                  (product.historyRates[0]?.dailyProfit || 0)).toFixed(2)}
              </TableCell>
            </TableRow>
          </TableBody>
        </Table>
      </TableContainer>

      <Typography variant="h6" gutterBottom>
        收益率走势
      </Typography>
      <Box mb={4}>
        <Line data={chartData} options={options} />
      </Box>

      <Typography variant="h6" gutterBottom>
        投资明细
      </Typography>
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>投资日期</TableCell>
              <TableCell align="right">投资金额</TableCell>
              <TableCell align="right">持有天数</TableCell>
              <TableCell align="right">预计收益</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {product.investments.map((investment) => (
              <TableRow key={investment.id}>
                <TableCell>
                  {new Date(investment.purchaseDate).toLocaleDateString()}
                </TableCell>
                <TableCell align="right">
                  ¥{investment.amount.toLocaleString()}
                </TableCell>
                <TableCell align="right">
                  {Math.floor((new Date().getTime() - 
                    new Date(investment.purchaseDate).getTime()) / 
                    (1000 * 60 * 60 * 24))}
                </TableCell>
                <TableCell align="right">
                  ¥{((investment.amount * calculation.dailyRate * 
                    Math.floor((new Date().getTime() - 
                    new Date(investment.purchaseDate).getTime()) / 
                    (1000 * 60 * 60 * 24))).toFixed(2))}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </Box>
  );
};

export default YieldCalculator;